package com.quick.proxy.server.handler.visitor;

import cn.hutool.json.JSONUtil;
import com.quick.proxy.core.CmdTypeConstants;
import com.quick.proxy.core.ForwardMessage;
import com.quick.proxy.core.ProxyChannel;
import com.quick.proxy.core.utils.ByteUtils;
import com.quick.proxy.core.utils.ProtocolUtils;
import com.quick.proxy.server.ServerChannelAttribute;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * Description: 访问者代理服务器协议处置处理程序
 * Author: 吃素不吃肉
 * Date: 2023/7/9
 *
 * @author 吃素不吃肉
 */
@Slf4j
@Sharable
@Component
public class VisitorProxyServerProtocolDisposeHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("visitor proxy server system error.", cause);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg != null) {
            byte[] bytes = (byte[]) msg;
            ProxyChannel proxyChannel = ctx.channel().attr(ServerChannelAttribute.PROXY_CHANNEL).get();
            if (proxyChannel != null) {
                ForwardMessage forwardMessage = new ForwardMessage();
                forwardMessage.setVisitorId(proxyChannel.getVisitorId());
                forwardMessage.setBytes(bytes);
                proxyChannel.getProxyChannel().writeAndFlush(ProtocolUtils.getByte(CmdTypeConstants.FORWARD, JSONUtil.toJsonStr(forwardMessage).getBytes(StandardCharsets.UTF_8)));
                log.debug("visitorId[{}]Send proxy messages:{}", proxyChannel.getVisitorId(), ByteUtils.bytesToHex(bytes));
            } else {
                ctx.channel().close();
            }
        }
    }

}
